/* 
 * File:   resource.c
 * Author: bjorn
 *
 * Created on September 3, 2007, 8:13 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "object.h"
#include "memory.h"
#include "script.h"
#include "rope.h"
#include "image.h"
#include "resource.h"
/*
 * 
 */



Resource resource_free(Resource self) {
	if(!self) return NULL;	
	rope_free(self->path);
	rope_free(self->config);
	ropelist_free(self->directories);	
	script_free(self->script);
	return NULL;
}

Resource resource_scan(Resource self) {
  	int stop = ropelist_size(self->directories);
  	int index = 0;
  	for (index = 0; index < stop; index++) {
    	Rope path = ropelist_get(self->directories, index);
    	if(file_exists(rope_c(path))) {
			self->config = rope_clone(path);
			/* path does not need to be deallocated as it is a direct pointer, not a copy; */
			return self;
		}
  	}
	return NULL;
}

Resource resource_run_script(Resource self) {
	Script ok = script_run(self->script,rope_c(self->config));
	if(!ok) return NULL;
	return self;
} 

Resource resource_make() {
	char * homestr 	= getenv("ERUTA_HOME");
	Resource result = memory_make(Resource);
	result->script  = script_make();
	result->path	= rope_make(ERUTA_RESOURCE_PATH); 
	if(homestr) {
		rope_cat_c(result->path,  ERUTA_PATH_SEP_STR);
		rope_cat_c(result->path, homestr);
	}
	result->directories = rope_split_c(result->path, ERUTA_PATH_SEP_CHAR);
	if(!resource_scan(result)) {
		return resource_free(result);
	}
	script_setglob_string(result->script, "ERUTA_CONFIG", rope_c(result->config) );

	return resource_run_script(result);
}	


Image resource_loadimage_c(Resource self, char * imagename) {
	Rope name;
	Image result;	
	name = script_get_rope(self->script, "ERUTA_IMAGE_DIR", "./share/image/");
    rope_cat_c(name, imagename);
	result = image_load_c(rope_c(name));
	rope_free(name);
	return result;
}

bool file_exists(char *filename) {
    FILE * file;
    file = fopen(filename, "r");
    if(!file) return false;
    fclose(file);
    return true;
}

char * resource_filename(const char * name) {
     return NULL;
} 


FILE * resource_file_open(char * name) {
    return NULL;
}

